<template>
  <n-drawer v-model:show="isDrawer" :width="width" :auto-focus="false" @after-leave="handleReset">
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
      >

        <n-form-item label="充电宝编号" path="charger_number">
          <n-input
            placeholder="请输入充电宝编号"
            v-model:value="formParams.charger_number"
          />
        </n-form-item>

        <n-form-item label="充电宝名称" path="charger_name">
          <n-input placeholder="请输入充电宝名称" v-model:value="formParams.charger_name" />
        </n-form-item>
        
        <n-form-item label="充电宝协议" path="charger_type">
          <n-select clearable placeholder="请选择充电宝协议" v-model:value="formParams.charger_type" label-field="name" value-field="id" :options="deviceTypeAll"/>
        </n-form-item>

        <!-- <n-form-item label="充电宝类型" path="charger_kind">
          <n-select clearable placeholder="请选择充电宝类型" v-model:value="formParams.charger_kind" label-field="name" value-field="id" :options="deviceKindAll" @update:value="chargerKindChange"/>
        </n-form-item> -->

        <!-- <n-form-item label="充电宝类型" path="charger_kind">
          <n-select clearable filterable placeholder="请选择充电宝类型" v-model:value="formParams.charger_kind" label-field="title" value-field="id" :options="deviceKindAll"/>
        </n-form-item> -->
        
        <n-form-item label="归属代理商">
          <n-input placeholder="请选择归属代理商" disabled v-model:value="formParams.charger_agents_name" />
          <n-button type="primary" @click="handleAgent" ghost>
            选择代理商
          </n-button>
        </n-form-item>

        <n-form-item label="归属商户">
          <n-input placeholder="请选择归属商户" disabled v-model:value="formParams.charger_bussiness_name" />
          <n-button type="primary" @click="handleBusinesses" ghost>
            选择商户
          </n-button>
        </n-form-item>

        <n-form-item label="所属门店">
          <n-input placeholder="请选择所属门店" disabled v-model:value="formParams.charger_station_name" />
          <n-button type="primary" @click="handleStation" ghost>
            选择所属门店
          </n-button>
        </n-form-item>

        <n-form-item label="状态" path="charger_status">
          <n-radio-group v-model:value="formParams.charger_status" name="statusGroup">
            <n-space>
              <n-radio :key="1" :value="1">启用</n-radio>
              <n-radio :key="2" :value="2">禁用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

      </n-form>

      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>

      <n-modal v-model:show="showModal">
        <n-card
          style="width: 600px"
          title="选择代理商"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="chargerParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="chaSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>代理商名称</th>
              <th>代理商账号</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in agentAll" :key="index">
              <td>{{item.nickname}}</td>
              <td>{{item.username}}</td>
              <td><n-button type="primary" @click="selectAgent(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="chargerParams.page"
              v-model:page-size="chargerParams.pageSize"
              :page-count="chargerParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="chargerChangePage"
              :on-update-page-size="chargerChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="showStationModal">
        <n-card
          style="width: 600px"
          title="选择门店"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="stationAllParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="stationAllList">搜索</n-button>
            </div>
          <div v-if="stationAll.length==0">
            该用户下没有门店请去添加门店
          </div>

          <n-table v-else :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>门店名称</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in stationAll" :key="index">
              <td>{{item.name}}</td>
              <td><n-button type="primary" @click="selectStation(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="stationAllParams.page"
              v-model:page-size="stationAllParams.pageSize"
              :page-count="stationAllParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="stationAllChangePage"
              :on-update-page-size="stationAllChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="businessesModal">
        <n-card
          style="width: 600px"
          title="选择商户"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
              <div style="width: 50px;">名称：</div>
                <n-input
                  style="width: 50%;"
                  v-model:value="stationParams.name"
                  clearable
                  placeholder="请输入名称"
                />
                <n-button style="margin-left: 10px" @click="staSearchBut">搜索</n-button>
          </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>商户名称</th>
                <th>商户账号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in businessesAll" :key="index">
                <td>{{item.nickname}}</td>
                <td>{{item.username}}</td>
                <td><n-button type="primary" @click="selectBusinesses(item)">选择</n-button></td>
              </tr>
            </tbody>
            
          </n-table>
          <n-pagination
              v-model:page="stationParams.page"
              v-model:page-size="stationParams.pageSize"
              :page-count="stationParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="stationChangePage"
              :on-update-page-size="stationChangePagesize"
            />
        </n-card>
      </n-modal>

    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import type { formParamsType } from './types';
  import { useDictionary } from '@/hooks/web/useDictionary';
  import { getallStationList,addCharger,editCharger,chargerInfo,getDeviceTypeList,bussinessCharger,getStationList1,banklistnopage} from '@/api/device/charger';
  import { getallagentList,getallagentList1 } from '@/api/system/user';

  const rules: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    nickname: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    },
    roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'number',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);
  const { getDictTypeList } = useDictionary();

  const props = defineProps({
    title: {
      type: String,
      default: '添加充电宝',
    },
    width: {
      type: Number,
      default: 850,
    },
    roleList: {
      type: Array,
    },
  });

  const defaultValueRef = () => ({
    id: null,
    charger_number: '',
    charger_name: '',
    charger_type: '',
    // charger_kind: '',
    charger_agents_name: '',
    charger_agents_id: 0,
    charger_station_name: '',
    charger_station_id: 0,
    charger_status: 1,
    charger_bussiness_id: 0,
    charger_bussiness_name: ''
  });

  const format = ref("yyyy-MM-dd HH:mm:ss");
  const stationAll = ref([]);
  const showModal = ref(false);
  const showStationModal = ref(false);
  const businessesModal = ref(false);
  const businessesAll = ref([]);
  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const agentAll = ref([]);
  const deviceTypeAll = ref([]);
  const deviceKindAll = ref();
  const formParams = ref<formParamsType>(defaultValueRef());

  const chargerParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const stationParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const stationAllParams = ref({
    name: '',
    page: 1,
    pageSize: 10,
    totalPage: 1,
    charger_agents_id: 0,
    charger_bussiness_id: 0
  });

  function handleStation(){
    showStationModal.value = true;
  }

  function handleAgent(){
    showModal.value = true;
  }

  function handleBusinesses(){
    businessesModal.value = true;
  }

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    formParams.value.charger_agents_id = 0;
    formParams.value.charger_agents_name = '';
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        const msg = formParams.value.id ? '编辑成功' : '添加成功';
        if (formParams.value.id) {
          editCharger(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          addCharger(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value.restoreValidation();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    chargerInfo({ id: formParams.value.id }).then((res) => {
      const params = {
        id: formParams.value.id,
        charger_number: res.charger_number,
        charger_name: res.charger_name,
        charger_type: res.charger_type,
        // charger_kind: res.charger_kind,
        charger_agents_name: res.charger_agents_name,
        charger_agents_id: res.charger_agents_id,
        charger_station_name: res.charger_station_name,
        charger_station_id: res.charger_station_id,
        charger_status: res.charger_status,
        charger_bussiness_id: res.charger_bussiness_id,
        charger_bussiness_name: res.charger_bussiness_name
      };

      formParams.value = Object.assign(formParams.value, params);
      stationAllList();
      isDrawer.value = true;
    });
  }

  function selectBusinesses(item){
    //商户id
    formParams.value.charger_bussiness_id = item.id;
    //商户名称
    formParams.value.charger_bussiness_name = item.username;
    
    businessesModal.value = false;

    //门店搜索
    stationAllList();
  }

  function selectStation(item){
    formParams.value.charger_station_id = item.id;
    formParams.value.charger_station_name = item.name;
    showStationModal.value = false;
  }

  async function selectAgent(item){
    //代理商id
    formParams.value.charger_agents_id = item.id;
    //代理商名称
    formParams.value.charger_agents_name = item.username;

    //商户id
    formParams.value.charger_bussiness_id = 0;
    //商户名称
    formParams.value.charger_bussiness_name = '';
    stationParams.value.charger_agents_id = item.id;

    //查询商户
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;

    //门店搜索
    stationAllList();
    showModal.value = false;
  }

  //代理商分页
  async function chargerChangePage(e){
    //改变一下页数
    chargerParams.value.page = e;
    //重新请求一下接口
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  async function chargerChangePagesize(e){
    //改变条数
    chargerParams.value.pageSize = e;

    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  //代理商搜索
  async function chaSearchBut(){
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }


  //商家搜索
  async function staSearchBut(){
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }

  //商家分页
  async function stationChangePage(e){
    //改变一下页数
    stationParams.value.page = e;
    //重新请求一下接口
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }

  async function stationChangePagesize(e){
    //改变条数
    stationParams.value.pageSize = e;

    var result = await bussinessCharger(stationParams.value);

    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }

  //门店分页
  async function stationAllChangePage(e){
    //改变一下页数
    stationAllParams.value.page = e;
    stationAllList();
  }
  async function stationAllChangePagesize(e){
    //改变条数
    stationAllParams.value.pageSize = e;
    stationAllList();
  }

  async function stationAllList(){
    if( formParams.value.charger_bussiness_id == 0 && formParams.value.charger_agents_id == 0 ){
      
    }else{//查询一下归属代理商的值

      stationAllParams.value.charger_agents_id = formParams.value.charger_agents_id;

      stationAllParams.value.charger_bussiness_id = formParams.value.charger_bussiness_id;
      
      var all123 = await getStationList1(stationAllParams.value);
      stationAllParams.value.totalPage = all123.totalPage;
      stationAll.value = all123.list;
    }
  }

  onMounted(async () => {
    //查询一下所有的代理商
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;

    //查询所有的设备类型
    var deviceType = await getDeviceTypeList({});
    deviceTypeAll.value = deviceType;

    //查询所有的设备类型
    var bankType = await banklistnopage({});
    deviceKindAll.value = bankType;
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
